# encoding: utf-8
from flask import (Blueprint,
                   views,
                   render_template,
                   request,
                   session,
                   url_for)
from .forms import SignupForm,SigninFrom
from utils import restful,safeutils
from exts import db
from .models import FrontUser
import config
from ..models import BannerModel,BoardModel


bp = Blueprint('front',__name__,)

@bp.route('/')
def index():
    banners = BannerModel.query.order_by(BannerModel.priority.desc()).limit(3)
    boards = BoardModel.query.all()
    context={
        'banners':banners,
        'boards':boards
    }
    return render_template('front/front_index.html',**context)


class SingupVews(views.MethodView):
    def get(self):
        return_to = request.referrer
        if return_to and return_to != request.url and safeutils.is_safe_url(return_to):
            return render_template('front/front_signup.html',return_to=return_to)
        else:
            return render_template('front/front_signup.html')
    def post(self):
        form = SignupForm(request.form)
        if form.validate():
            telephone = form.telephone.data
            username = form.username.data
            password = form.password1.data
            user = FrontUser(telephone=telephone,username=username,password=password)
            db.session.add(user)
            db.session.commit()
            return restful.success()
        else:
            return restful.params_error(message=form.get_error())

class SigninVews(views.MethodView):
    def get(self):
        # request.referrer 是上一步的url
        return_to = request.referrer
        # 验证 return_to
        if return_to and return_to != request.url and return_to != \
            url_for('front.signin') and safeutils.is_safe_url(return_to):
            return render_template('front/front_signin.html',return_to = return_to)
        else:
            return render_template('front/front_signin.html')
    def post(self):
        # request.form是js表单请求，先对前端数据进行验证，再提取出来
        form = SigninFrom(request.form)
        if form.validate():
            telephone = form.telephone.data
            password = form.password.data
            remember = form.remember.data
            # 根据手机号码查找数据
            user = FrontUser.query.filter(FrontUser.telephone == telephone).first()
            # 验证用户及密码
            if user and user.check_password(password):
                session[config.FRONT_USER_ID] = user.id
                if remember:
                    session.permanent = True
                return restful.success()
            else:
                return restful.params_error(message='手机或密码错误！')
        else:
            return restful.params_error(message=form.get_error())





bp.add_url_rule('/signup/',view_func=SingupVews.as_view('signup'))
bp.add_url_rule('/signin/',view_func=SigninVews.as_view('signin'))